<template>
  <view class="job-list-container">
    <!-- 顶部导航栏 -->
    <view class="top-bar">
      <view class="back-btn" @click="handleBack">
        <image src="/static/jiantou2_1.png" mode="aspectFit" class="back-icon"></image>
      </view>
      <text class="title">岗位管理</text>
      <view class="right-icon" style="color: #007AFF;" @click="handleAdd">
        <!-- <image src="/static/tianjia_2.png" mode="aspectFit" class="add-icon"></image> -->
         添加
      </view>
    </view>
    
    <!-- 岗位列表 -->
    <view class="job-list">
      <!-- 岗位列表项 -->
      <view class="job-item" v-for="(job, index) in jobs" :key="job.id" @click="handleJobClick(job)">
        <view class="job-info">
          <text class="job-name">{{ job.name }}</text>
          <text class="job-role">{{ getRoleText(job.role) }}</text>
        </view>
        <view class="job-remark" v-if="job.remark">{{ job.remark }}</view>
        <view class="job-action">
          <text class="job-time">{{ formatDate(job.createtime) }}</text>
          <view class="action-buttons">
            <view class="edit-btn" @click.stop="handleEdit(job)">
              <image src="/static/xiugai07_1.png" mode="aspectFit" class="btn-icon"></image>
            </view>
            <view class="delete-btn" @click.stop="handleDelete(job)">
              <image src="/static/shanchu_1.png" mode="aspectFit" class="btn-icon"></image>
            </view>
          </view>
        </view>
        
        <!-- 子岗位列表 -->
        <view class="sub-jobs" v-if="job.children && job.children.length > 0">
          <view class="sub-job-item" v-for="subJob in job.children" :key="subJob.id" @click.stop="handleJobClick(subJob)">
            <view class="sub-job-info">
              <text class="sub-job-name">{{ subJob.name }}</text>
              <text class="sub-job-role">{{ getRoleText(subJob.role) }}</text>
            </view>
            <view class="sub-job-action">
              <view class="edit-btn" @click.stop="handleEdit(subJob)">
                <image src="/static/xiugai07_1.png" mode="aspectFit" class="btn-icon"></image>
              </view>
              <view class="delete-btn" @click.stop="handleDelete(subJob)">
                <image src="/static/shanchu_1.png" mode="aspectFit" class="btn-icon"></image>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="jobs.length === 0 && !loading">
        <image src="/static/empty.png" mode="aspectFit" class="empty-icon"></image>
        <text class="empty-text">暂无岗位信息</text>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 分页 -->
    <view class="pagination" v-if="jobs.length > 0 && !loading">
      <button class="page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">上一页</button>
      <text class="page-info">{{ currentPage }}/{{ totalPages }}</text>
      <button class="page-btn" :disabled="currentPage >= totalPages" @click="changePage(currentPage + 1)">下一页</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      jobs: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      totalCount: 0,
      roleMap: {
        '1': '管理员',
        '2': '店长',
        '3': '副店长',
        '4': '员工'
      }
    };
  },
  onShow() {
    this.getJobList();
  },
  methods: {
    // 返回上一页
    handleBack() {
      uni.navigateBack();
    },
    // 获取岗位列表
    async getJobList() {
      try {
        this.loading = true;
        const res = await this.$request({
          url: '/job/index',
          method: 'GET',
          params: {
            page: this.currentPage,
            limit: this.pageSize
          }
        });
        
        if (res.code === 1) {
          // 扁平化岗位数据，方便展示
          this.flattenJobs(res.data);
          // 计算总页数
          this.totalCount = res.data.length;
          this.totalPages = Math.ceil(this.totalCount / this.pageSize);
        } else {
          throw new Error(res.msg || '获取岗位列表失败');
        }
      } catch (error) {
        console.error('获取岗位列表失败:', error);
        uni.showToast({
          title: error.message || '获取岗位列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 扁平化岗位数据
    flattenJobs(jobData) {
      const flatJobs = [];
      
      const flatten = (jobs) => {
        jobs.forEach(job => {
          flatJobs.push({
            ...job,
            // 为了分页显示，我们先只取顶层岗位
            children: null
          });
          
          // 如果需要显示所有层级，可以取消下面的注释
          /*
          if (job.children && job.children.length > 0) {
            job.children.forEach(child => {
              flatJobs.push({
                ...child,
                isSubJob: true,
                parentId: job.id
              });
              if (child.children && child.children.length > 0) {
                flatten(child.children);
              }
            });
          }
          */
        });
      };
      
      flatten(jobData);
      
      // 分页处理
      this.jobs = flatJobs.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    
    // 获取角色文本
    getRoleText(role) {
      return this.roleMap[role] || '未知角色';
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 切换分页
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
      this.getJobList();
    },
    
    // 点击岗位查看详情
    handleJobClick(job) {
      uni.navigateTo({
        url: `/pages/joblist/components/jobdetail?id=${job.id}`
      });
    },
    
    // 编辑岗位
    handleEdit(job) {
      uni.navigateTo({
        url: `/pages/joblist/components/jobedit?id=${job.id}`
      });
    },
    
    // 添加岗位
    handleAdd() {
      uni.navigateTo({
        url: '/pages/joblist/components/jobedit'
      });
    },
    
    // 删除岗位
    handleDelete(job) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除岗位 "${job.name}" 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await this.$request({
                url: '/job/del',
                method: 'POST',
                data: {
                  ids: job.id
                }
              });
              
              if (result.code === 1) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新获取岗位列表
                this.getJobList();
              } else {
                throw new Error(result.msg || '删除失败');
              }
            } catch (error) {
              console.error('删除岗位失败:', error);
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.job-list-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}
/* 顶部导航栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.add-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 岗位列表 */
.job-list {
  padding: 20rpx;
}

/* 岗位列表项 */
.job-item {
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.job-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.job-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.job-role {
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.job-remark {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
  line-height: 1.5;
}

.job-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.job-time {
  font-size: 24rpx;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.btn-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 子岗位列表 */
.sub-jobs {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx dashed #eee;
}

.sub-job-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.sub-job-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.sub-job-name {
  font-size: 28rpx;
  color: #333;
  margin-left: 20rpx;
  position: relative;
}

.sub-job-name::before {
  content: '';
  position: absolute;
  left: -20rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  background-color: #4cd964;
}

.sub-job-role {
  font-size: 22rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 50rpx;
  height: 50rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #4cd964;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40rpx;
  padding: 30rpx;
  background-color: #fff;
  margin-top: 20rpx;
}

.page-btn {
  padding: 12rpx 40rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 30rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}
</style>